use crate::db::dao::segment_list::SegmentListDao;
use crate::db::{dao, po};
use crate::dto;
use crate::service::Error;
use std::sync::Arc;
use wanmesh_common::error::ResponseError;

#[async_trait::async_trait]
pub trait SegmentLisService: Send + Sync {
    async fn add(
        &self,
        params: &dto::core::segment_list::AddParams,
    ) -> Result<dto::core::segment_list::AddResponseData, Error>;

    async fn list(
        &self,
        filter: &dto::core::segment_list::Filter,
        offset: u64,
        limit: u64,
    ) -> Result<Vec<dto::core::segment_list::SegmentListItem>, Error>;

    async fn get(
        &self,
        segment_list_id: &str,
    ) -> Result<dto::core::segment_list::SegmentListItem, Error>;

    async fn try_get(
        &self,
        segment_list_id: &str,
    ) -> Result<Option<dto::core::segment_list::SegmentListItem>, Error>;

    async fn update(
        &self,
        segment_list_id: &str,
        params: &dto::core::segment_list::UpdateParams,
    ) -> Result<(), Error>;

    async fn delete(&self, segment_list_id: &str) -> Result<(), Error>;

    async fn count(&self, filter: &dto::core::segment_list::Filter) -> Result<u64, Error>;
}

pub struct DefaultSegmentListService {
    segment_list_dao: Arc<dyn SegmentListDao>,
}

impl DefaultSegmentListService {
    pub fn new(segment_list_dao: Arc<dyn SegmentListDao>) -> Self {
        DefaultSegmentListService { segment_list_dao }
    }
}

#[async_trait::async_trait]
impl SegmentLisService for DefaultSegmentListService {
    async fn add(
        &self,
        params: &dto::core::segment_list::AddParams,
    ) -> Result<dto::core::segment_list::AddResponseData, Error> {
        let segment_list_id = wanmesh_common::util::new_id()?;
        self.segment_list_dao
            .insert(po::segment_list::ActiveModel {
                id: Default::default(),
                segment_list_id: po::ActiveValue::Set(segment_list_id.clone()),
                name: po::ActiveValue::Set(params.name.clone()),
                description: po::ActiveValue::Set(params.description.clone()),
                create_timestamp_millis: Default::default(),
                update_timestamp_millis: Default::default(),
            })
            .await?;

        Ok(dto::core::segment_list::AddResponseData { segment_list_id })
    }
    async fn list(
        &self,
        filter: &dto::core::segment_list::Filter,
        offset: u64,
        limit: u64,
    ) -> Result<Vec<dto::core::segment_list::SegmentListItem>, Error> {
        
        let po_list = self
            .segment_list_dao
            .find(dao::FindParams {
                filter: filter.into(),
                offset: Some(offset),
                limit: Some(limit),
                ..Default::default()
            })
            .await?;

        let list = po_list.into_iter().map(|po| po.into()).collect();
        Ok(list)
    }

    async fn get(
        &self,
        segment_list_id: &str,
    ) -> Result<dto::core::segment_list::SegmentListItem, Error> {
        let segment_list = self
            .try_get(segment_list_id)
            .await?
            .ok_or(ResponseError::segment_list_not_found(segment_list_id))?;
        Ok(segment_list)
    }

    async fn try_get(
        &self,
        segment_list_id: &str,
    ) -> Result<Option<dto::core::segment_list::SegmentListItem>, Error> {
        let filter = dao::segment_list::Filter {
            segment_list_id: Some(segment_list_id.to_string()),
            ..Default::default()
        };

        if let Some(m) = self.segment_list_dao.try_get(filter).await? {
            return Ok(Some(m.into()));
        }

        Ok(None)
    }

    async fn update(
        &self,
        segment_list_id: &str,
        params: &dto::core::segment_list::UpdateParams,
    ) -> Result<(), Error> {
        if params == &Default::default() {
            return Ok(());
        }

        let filter = dao::segment_list::Filter {
            segment_list_id: Some(segment_list_id.to_string()),
            ..Default::default()
        };

        self.segment_list_dao.update(filter, params.into()).await?;

        Ok(())
    }

    async fn delete(&self, segment_list_id: &str) -> Result<(), Error> {
        let filter = dao::segment_list::Filter {
            segment_list_id: Some(segment_list_id.to_string()),
            ..Default::default()
        };

        self.segment_list_dao.delete(filter).await?;

        Ok(())
    }

    async fn count(&self, filter: &dto::core::segment_list::Filter) -> Result<u64, Error> {
        let count = self.segment_list_dao.count(filter.into()).await?;

        Ok(count)
    }
}

impl From<&dto::core::segment_list::Filter> for dao::segment_list::Filter {
    fn from(value: &dto::core::segment_list::Filter) -> Self {
        Self {
            segment_list_id: None,
            name: value.name.clone(),
        }
    }
}

impl From<dto::core::segment_list::Filter> for dao::segment_list::Filter {
    fn from(value: dto::core::segment_list::Filter) -> Self {
        Self::from(&value)
    }
}

impl From<&dto::core::segment_list::UpdateParams> for dao::segment_list::UpdateParams {
    fn from(value: &dto::core::segment_list::UpdateParams) -> Self {
        Self {
            name: po::option_to_active_value(value.name.clone()),
            description: po::option_to_active_value(value.description.clone()),
        }
    }
}

impl From<&po::segment_list::Model> for dto::core::segment_list::SegmentListItem {
    fn from(value: &po::segment_list::Model) -> Self {
        Self {
            segment_list_id: value.segment_list_id.clone(),
            inner: dto::core::segment_list::SegmentList {
                name: value.name.clone(),
                description: value.description.clone(),
            },
        }
    }
}

impl From<po::segment_list::Model> for dto::core::segment_list::SegmentListItem {
    fn from(value: po::segment_list::Model) -> Self {
        Self::from(&value)
    }
}
